$(function(){
    $('input').iCheck({checkboxClass: 'icheckbox_square-blue',radioClass: 'iradio_square-blue',increaseArea: '20%'});

    getGoods();

    $('[name="propertyValue"]').on('ifChanged',function(){getGoods()});
    $('#hasGoods').on('ifChanged',function(){getGoods()});
    $('#certainPrice').click(function(){
        getGoods();
    });
    $("#orderBySalesVolume").click(function(){
        if($(this).hasClass('current')){
            if($(this).html().indexOf("↓")>=0){
                $(this).html("<a>销量 ↑</a>");
            }else{
                $(this).html("<a>销量 ↓</a>");
            }
        }else{
            $('.shop-cmp-l.f-l .current').removeClass("current");
            $(this).addClass("current");
        }
        getGoods();
    });
    $("#orderByPrice").click(function(){
        if($(this).hasClass('current')){
            if($(this).html().indexOf("↓")>=0){
                $(this).html("<a>价格 ↑</a>");
            }else{
                $(this).html("<a>价格 ↓</a>");
            }
        }else{
            $('.shop-cmp-l.f-l .current').removeClass("current");
            $(this).addClass("current");
        }
        getGoods();
    });
    $("#orderByComment").click(function(){
        if($(this).hasClass('current')){
            if($(this).html().indexOf("↓")>=0){
                $(this).html("<a>评论 ↑</a>");
            }else{
                $(this).html("<a>评论 ↓</a>");
            }
        }else{
            $('.shop-cmp-l.f-l .current').removeClass("current");
            $(this).addClass("current");
        }
        getGoods();
    });
});

//默认根据当前界面所有条件（除了页码）获得第一页的商品，相当于刷新，但加入page参数则可以使其获得相应页码的数据
function getGoods(page){
    var params = {};
    /*
        params = {
     sql未处理：,orderBy,order,page
     sql已处理：goodTypeId,minPrice,maxPrice,hasGoods,goodTypePropertyValue
        }
     */
    params.goodTypeId = $("#goodTypeId").val();//参数：商品类型ID

    var a = $('[name="propertyValue"]:checked').map(function(){return parseInt($(this).val())});
    var goodTypePropertyValue = "";
    for(var i=0;i< a.length;i++){
        goodTypePropertyValue = ","+a[i];
    }
    goodTypePropertyValue = goodTypePropertyValue.substr(1);
    params.goodTypePropertyValue = goodTypePropertyValue;//参数：商品属性值ID，字符串（逗号分隔）

    var orderBy;
    var order;
    if($('#orderBySalesVolume').hasClass("current")){//销量排序
        orderBy = "salesVolume";
        if($('#orderBySalesVolume').html().indexOf("↓")<0)
            order = "asc";
        else
            order = "desc";
    }else if($('#orderByPrice').hasClass("current")){//价格排序
        orderBy = "price";
        if($('#orderByPrice').html().indexOf("↓")<0)
            order = "asc";
        else
            order = "desc";
    }else if($('#orderByComment').hasClass("current")){//评论排序
        orderBy = "salesVolume";//TODO:现在是按照销量排序，以后要改回按评论排序
        if($('#orderByComment').html().indexOf("↓")<0)
            order = "asc";
        else
            order = "desc";
    }
    params.orderBy = orderBy;//参数：排序列
    params.order = order;//参数：排序的顺序

    params.minPrice = $("#minPrice").val();//参数：最小价格
    params.maxPrice = $("#maxPrice").val();//参数：最大价格

    params.hasGoods = $('#hasGoods').is(':checked')?1:0;//参数：显示有货

    params.page = page;//参数：页码

    $.ajax({
        url:ctx+'/good/search.do',
        data:params,
        success:function(data){
            /*data={
             currentPage:1,
             maxPage:10,
             goodList:[
             {
             id:1,
             photoId:1,
             price:10.5,
             name:nabati,
             shopId:shopId,
             stock:1000,
             shopName:'盼盼食品',
             commentCount:100//评论数目
             },{}

             ]
             }*/
            $('#goodGrid').html("");
            $('#kkpager').html("").parent().append('<script type="text/javascript" src="/home/assets/kkpager/js/kkpager.js"></script>').append('<script>' +
                'kkpager.generPageHtml({' +
                'pno : ' +data.currentPage+','+
                'mode : "click",' +
                'total : ' + data.maxPage+','+
                'click : function(n){' +
                    'getGoods(n);' +
                    'this.selectPage(n);' +
                '}' +
                '});</script>');

            setTimeout(function(){
                $(".paging").width($(".pageBtnWrap").width()+$(".infoTextAndGoPageBtnWrap").width()+20);
            },1500);

            var goodList = data.goodList;
            var good;
            for(var i=0;i<goodList.length;i++){
                good = goodList[i];
                var li = (i+1)%5==0?'<li style="margin-right:0px;">':'<li>'
                $('#goodGrid').append(li +
                    '<div class="li-top">' +
                        '<a href="/good/detail.do?code='+good.code+'" class="li-top-tu"><img height=140 src="'+ctx+'/resource/download.do?id='+good.photoId+'" /></a>' +
                        '<p class="jiage">' +
                            '<span class="sp1">￥'+good.price+'</span>' +
                        '</p>' +
                    '</div>' +
                    '<p class="miaoshu">'+good.name+'</p>' +
                    '<div class="li-md">' +
                        '<div class="md-l f-l">' +
                            '<p class="md-l-l f-l" ap="">1</p>' +
                            '<div class="md-l-r f-l">' +
                                '<a onclick="increase(this)" style="cursor:pointer" class="md-xs" at="">∧</a>' +
                                '<a onclick="decrease(this)" style="cursor:pointer" class="md-xx" ab="">∨</a>' +
                            '</div>' +
                            '<div style="clear:both;"></div>' +
                        '</div>' +
                        '<div class="md-r f-l">' +
                            '<button class="md-l-btn1">立即购买</button>' +
                            '<button class="md-l-btn2" onclick="addCart(this,'+good.id+')">加入购物车</button>' +
                        '</div>' +
                        '<div style="clear:both;"></div>' +
                    '</div>' +
                    '<p class="pingjia">'+good.commentCount+'评价</p>' +
                    '<p class="weike">'+good.shopName+'</p>' +
                 '</li>');
            }
        }
    })

}
function increase(me){
    var p = $(me).parent().siblings('p');
    p.html(parseInt(p.html())+1);
}

function decrease(me){
    var p = $(me).parent().siblings('p');
    if(parseInt(p.html())>0)
        p.html(parseInt(p.html())-1)
}

function addCart(me,goodId){
    if($("#userId").length==0)
        alert("请先登录")
    var num = $(me).parent().parent().children().eq(0).children().eq(0).html();
    $.ajax({
        url : ctx+'/shoppingCart/add.do',
        data : {
            goodId:goodId,
            num:num
        },
        success : function(data){
            if(data.flag>0)
                alert('操作成功');
            else
                alert('操作失败');
        }
    });
}